<template>
  <div class="movie-comparison">
    <a-card class="mb-4">
      <template #title>
        <span class="card-title">数据对比</span>
        <a-space class="float-right">
          <a-button type="primary" @click="fetchData">
            <template #icon><ReloadOutlined /></template>
            刷新数据
          </a-button>
        </a-space>
      </template>
      
      <!-- 数据加载中状态 -->
      <div v-if="loading" class="text-center py-8">
        <a-spin tip="数据加载中..."/>
      </div>
      
      <!-- 数据展示表格 -->
      <div v-else>
        <a-table
          :columns="columns"
          :data-source="comparisonData"
          :scroll="{ x: 1500 }"
          :pagination="{ 
            pageSize: 10,
            showTotal: total => `共 ${total} 条数据`
          }"
        >
          <!-- 自定义列渲染 -->
          <template #bodyCell="{ column, text, record }">
            <!-- 对比状态列 -->
            <template v-if="column.dataIndex === 'status'">
              <a-tag :color="getStatusColor(record)">
                {{ getStatusText(record) }}
              </a-tag>
            </template>
            
            <!-- 差异高亮显示 -->
            <template v-else-if="isDifferent(record, column.dataIndex)">
              <div class="comparison-cell">
                <div class="original-value">{{ record[column.dataIndex] }}</div>
                <div class="cleaned-value">{{ record[`cleaned_${column.dataIndex}`] }}</div>
              </div>
            </template>
          </template>
        </a-table>
      </div>
    </a-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { ReloadOutlined } from '@ant-design/icons-vue'
import { getMovies, getCleanedMovies } from '@/api/movie'

// 定义表格列
const columns = [
  {
    title: '电影名称',
    dataIndex: 'movie_name',
    width: 200,
    fixed: 'left'
  },
  {
    title: '发行信息',
    dataIndex: 'release_info',
    width: 150,
    customRender: ({ text, record }) => {
      if (record.status === 'original') {
        return text
      }
      return (
        <div class="comparison-cell">
          {text && <div class="original-value">{text}</div>}
          {record.cleaned_release_info && (
            <div class="cleaned-value">{record.cleaned_release_info}</div>
          )}
        </div>
      )
    }
  },
  {
    title: '分账占比',
    dataIndex: 'split_box_rate',
    width: 120,
    customRender: ({ text, record }) => {
      if (record.status === 'original') {
        return text
      }
      return (
        <div class="comparison-cell">
          {text && <div class="original-value">{text}</div>}
          {record.cleaned_split_box_rate && (
            <div class="cleaned-value">{record.cleaned_split_box_rate}</div>
          )}
        </div>
      )
    }
  },
  {
    title: '场次',
    dataIndex: 'show_count',
    width: 100,
    customRender: ({ text, record }) => {
      if (record.status === 'original') {
        return text
      }
      return (
        <div class="comparison-cell">
          {text && <div class="original-value">{text}</div>}
          {record.cleaned_show_count && (
            <div class="cleaned-value">{record.cleaned_show_count}</div>
          )}
        </div>
      )
    }
  },
  {
    title: '场次占比',
    dataIndex: 'show_count_rate',
    width: 120,
    customRender: ({ text, record }) => {
      if (record.status === 'original') {
        return text
      }
      return (
        <div class="comparison-cell">
          {text && <div class="original-value">{text}</div>}
          {record.cleaned_show_count_rate && (
            <div class="cleaned-value">{record.cleaned_show_count_rate}</div>
          )}
        </div>
      )
    }
  },
  {
    title: '总票房',
    dataIndex: 'sum_box_desc',
    width: 150,
    customRender: ({ text, record }) => {
      if (record.status === 'original') {
        return text
      }
      return (
        <div class="comparison-cell">
          {text && <div class="original-value">{text}</div>}
          {record.cleaned_sum_box_desc && (
            <div class="cleaned-value">{record.cleaned_sum_box_desc}</div>
          )}
        </div>
      )
    }
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: 100,
    fixed: 'right',
    customRender: ({ record }) => {
      const color = getStatusColor(record)
      const text = getStatusText(record)
      return <a-tag color={color}>{text}</a-tag>
    }
  }
]

// 数据状态
const loading = ref(false)
const comparisonData = ref([])

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const [originalRes, cleanedRes] = await Promise.all([
      getMovies(), // 获取原始数据
      getCleanedMovies() // 获取清洗后的数据
    ])
    
    console.log('原始数据:', originalRes)
    console.log('清洗后数据:', cleanedRes)
    
    if (originalRes.status === 'success' && cleanedRes.status === 'success') {
      // 合并数据进行对比
      comparisonData.value = mergeData(originalRes.data, cleanedRes.data)
    } else {
      message.error('获取数据失败')
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    message.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 合并原始数据和清洗后的数据
const mergeData = (original, cleaned) => {
  console.log('合并数据 - 原始数据:', original)
  console.log('合并数据 - 清洗后数据:', cleaned)
  
  const merged = []
  const processedIds = new Set()
  
  // 处理原始数据
  original.forEach(item => {
    const cleanedItem = cleaned.find(c => c.movie_name === item.movie_name)
    if (cleanedItem) {
      merged.push({
        key: item.id,  // 添加key属性
        ...item,
        cleaned_release_info: cleanedItem.release_info,
        cleaned_split_box_rate: cleanedItem.split_box_rate,
        cleaned_show_count: cleanedItem.show_count,
        cleaned_show_count_rate: cleanedItem.show_count_rate,
        cleaned_sum_box_desc: cleanedItem.sum_box_desc,
        status: 'changed'
      })
      processedIds.add(cleanedItem.id)
    } else {
      merged.push({
        key: item.id,  // 添加key属性
        ...item,
        status: 'original'
      })
    }
  })
  
  // 添加仅在清洗后数据中存在的记录
  cleaned.forEach(item => {
    if (!processedIds.has(item.id)) {
      merged.push({
        key: `new_${item.id}`,  // 为新数据添加唯一key
        movie_name: item.movie_name,
        release_info: '',
        split_box_rate: '',
        show_count: '',
        show_count_rate: '',
        sum_box_desc: '',
        cleaned_release_info: item.release_info,
        cleaned_split_box_rate: item.split_box_rate,
        cleaned_show_count: item.show_count,
        cleaned_show_count_rate: item.show_count_rate,
        cleaned_sum_box_desc: item.sum_box_desc,
        status: 'new'
      })
    }
  })
  
  console.log('合并后的数据:', merged)
  return merged
}

// 判断字段是否有差异
const isDifferent = (record, field) => {
  return record[field] !== record[`cleaned_${field}`] && record[`cleaned_${field}`] !== undefined
}

// 获取状态颜色
const getStatusColor = (record) => {
  switch (record.status) {
    case 'changed': return 'warning'
    case 'new': return 'success'
    default: return 'default'
  }
}

// 获取状态文本
const getStatusText = (record) => {
  switch (record.status) {
    case 'changed': return '已清洗'
    case 'new': return '新增'
    default: return '原始'
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.movie-comparison {
  padding: 24px;
}

.card-title {
  font-size: 16px;
  font-weight: 500;
}

.comparison-cell {
  position: relative;
}

.original-value {
  color: #ff4d4f;
  text-decoration: line-through;
  font-size: 12px;
}

.cleaned-value {
  color: #52c41a;
  font-weight: 500;
}

:deep(.ant-table-thead > tr > th) {
  background-color: #fafafa;
  font-weight: 500;
}
</style> 